<?php
// | 订单
// +----------------------------------------------------------------------
// | Author: carl <469714167@qq.com>
// +----------------------------------------------------------------------
// | Datetime: 2017-8-29 17:55
// +----------------------------------------------------------------------

namespace app\ice\controller;

use think\Validate;
use think\Log;
use think\Db;
use think\Loader;
use think\Exception;
use app\ice\model\Order as OrderModel;
use app\ice\model\OrderGoods;
use app\ice\model\Goods;
use app\ice\model\Reputation;
use app\ice\model\ScoreLog;

class Prize extends Init
{
    private $OrderModel;
    private $OrderGoodsModel;
    private $areaModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->OrderModel = Loader::model('Order');
        $this->OrderGoodsModel = Loader::model('OrderGoods');
        $this->areaModel = Loader::model('Area');
    }

    public function Detail(){
        $param = input('post.');
        // $validate = [
        //     'orderId' => 'require',
        // ];
        // $result = $this->validate($param, $validate);
        // if (true !== $result) {
        //     return ['data' => '', 'code' => 400, 'msg' => '参数不正确或者参数不全', 'status' => false];
        // }
        $data = $this->OrderModel->getOrderDetail($param);
        if($data){
            if($data){
            $data['add_time'] = date('Y-m-d H:i:s',$data['add_time']);
            $logistics['shipping_code'] = $data['shipping_code'];
            $logistics['consignee'] = $data['consignee'];
            $logistics['mobile'] = $data['mobile'];
            $logistics['address'] = $data['province'].$data['city'].$data['district'].$data['address'];
            $orderInfo['goods_price'] = (int)$data['goods_price'];
            $orderInfo['shipping_price'] =  (int)$data['shipping_price'];
            $orderInfo['amountReal'] = $data['goods_price'] + $data['shipping_price'];
            $orderInfo['mobile'] = $data['mobile'];
            $goods = $this->OrderGoodsModel->getOrderGoods($data['order_id']);
            switch ($data['status']) {
                case 0:
                    $orderInfo['statusStr'] = '待付款';
                    $orderInfo['status'] = $data['status'];
                    break;
                case 1:
                    $orderInfo['statusStr'] = '待发货';
                    $orderInfo['status'] = $data['status'];
                    break;
                case 2:
                    $orderInfo['statusStr'] = '待收货';
                    $orderInfo['status'] = $data['status'];
                    break;
                case 3:
                    $orderInfo['statusStr'] = '待评价';
                    $orderInfo['status'] = $data['status'];
                    break;
                case 4:
                    $orderInfo['statusStr'] = '已完成';
                    $orderInfo['status'] = $data['status'];
                    break;
            }
            $data['logistics'] = $logistics;
            $data['orderInfo'] = $orderInfo;
            $data['logisticsTraces'] = json_decode($data['traces'],true);
            $data['goods'] = $goods;
        }
            returnInfo($this->rrbApiId,$data);
        }else{
            returnInfo($this->rrbApiId,[],'订单不存在',false,400);
        }
    }

    public function Reputation(){
        $param = input('post.');
        Db::startTrans();
        try{
            $Reputation  = new Reputation;
            foreach ($param['reputations']['reputations'] as $key => &$value) {
                $value['order_id'] = $param['reputations']['orderId'];
                $value['goods_id'] = $value['id'];
                $value['uid'] = $param['uid'];
                if($value['reputation'] == 2){
                    $goodsIds = $value['id'];
                }
                unset($value['id']);
            }
            // db::name('goods')->where('id','in',$goodsIds)->setInc('numberGoodReputation',1);
            $data = $Reputation->saveAll($param['reputations']['reputations']);
            $param['status'] = 4;
            $param['orderId'] = $param['reputations']['orderId'];
            $result = $this->OrderModel->saveOrder($param);
            $param['id'] = $param['reputations']['orderId'];
            $orderInfo = OrderModel::get($param['id']);
            $goodsInfos = $orderInfo->OrderGoods;
            $goodsInfos = array_column($goodsInfos, 'goods_num','goods_id');
            foreach ($goodsInfos as $key => $value) {
                db::name('goods')->where('id',$key)->setInc('sales_sum',$value);
                db::name('goods')->where('id',$key)->setInc('numberGoodReputation');
            }
            $orderDetail = $this->OrderModel->getOrderDetail($param);
            $score =  db('user_info')->where('id',$param['uid'])->setInc('score',(int)$orderDetail['goods_price']);
            $scoreData =[];
            array_push($scoreData, [
                'score'=>(int)$orderDetail['goods_price'],
                'mark'=>'评价订单',
                'type'=>1,
                'uid'=>$param['uid'],
                'addTime'=>time(),
                'updateTime'=>time(),
            ]);
            $inviter_id = $orderDetail['inviter_id'];
            if($inviter_id > 0){
                $inviterScore =  db('user_info')->where('id',$inviter_id)->setInc('score',100);
                array_push($scoreData, [
                    'score'=>100,
                    'mark'=>'推荐奖励',
                    'type'=>1,
                    'uid'=>$inviter_id,
                    'addTime'=>time(),
                    'updateTime'=>time()
                ]);
            }
            $scoreLog = new ScoreLog();
            $scoreRes = $scoreLog->saveAll($scoreData);
            if($data && $result && $orderDetail && $score && $scoreRes){
                Db::commit();
                return ['data' => $result, 'code' => 200, 'msg' => '查询成功', 'status' => true];
            }else{
                throw new Exception("Error Processing Request", 1);
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
            return ['data' => [], 'code' => 400, 'msg' => '订单状态不正确', 'status' => false];
        }
    }

    public function Statistics(){
        $param = input('post.');
        $data = $this->OrderModel->getStatistics($param['uid']);
        if($data){
            return ['data' => $data, 'code' => 200, 'msg' => '查询成功', 'status' => true];
        }else{
            return ['data' => [], 'code' => 400, 'msg' => '订单不存在', 'status' => false];
        }
    }

    public function lists(){
        $param = input('post.');
        $page = $param['page'] ? $param['page'] : 1;
        $orll_page = config('paginate.list_rows'); 
        $data = $this->OrderModel->getPrizeOrder($param['uid'],$page,$orll_page);
        if($data){
            return ['data' => $data, 'code' => 200, 'msg' => '查询成功', 'status' => true];
        }else{
            return ['data' => [], 'code' => 400, 'msg' => '订单不存在', 'status' => false];
        }
    }

    public function Create(){
        $param = input('post.');
        // 启动事务
        Db::startTrans();
        try{
        $goodsList = json_decode($param['goodsJsonStr'],true);
        $goodsArr = array_column($goodsList, 'number','goodsId');
        $goodsIds = array_column($goodsList, 'goodsId');
        $inviterIds = array_column($goodsList, 'inviter_id');
        $goods  = db::name('goods')->field('id,price')->where('id','in',$goodsIds)->select();
        $price = 0;
        foreach ($goods as $key => $value) {
            if(array_key_exists($value['id'], $goodsArr)){
                $price += $goodsArr[$value['id']] * (int)$value['price'];
            }
        }
        if(isset($param['calculate']) && $param['calculate']){
            $result = [];
            $result['isNeedLogistics'] = 1;
            $result['goods_price'] = $price;
            $result['shipping_price'] = 0;
            return ['data' => $result, 'code' => 200, 'msg' => '查询成功', 'status' => true];
        }
        
        
        $order  = new OrderModel();
        $order->province     = $this->areaModel->getName($param['provinceId']);
        $order->city     = $this->areaModel->getName($param['cityId']);
        $order->district     = $this->areaModel->getName($param['districtId']);
        $order->address    = $param['address'];
        $order->consignee    = $param['linkMan'];
        $order->code    = $param['code'];
        $order->mobile    = $param['mobile'];
        $order->goods_price    = $price;
        $order->uid    = $param['uid'];
        $order->add_time    = time();
        $order->status    = 0;
        $order->order_sn    = time().rand(000000,999999);
        $order->address    = $param['address'];
        $order->inviter_id = array_sum($inviterIds) > 0  ? array_sum($inviterIds) : 0;
        $order->save();
        // 获取自增ID
        $OrderGoods  = new OrderGoods;
        foreach ($goods as $key => &$value) {
            $value['order_id'] = $order->order_id;
            if(array_key_exists($value['id'], $goodsArr)){
                $value['goods_num'] = $goodsArr[$value['id']];
            }
            $value['goods_id'] = $value['id'];
            $value['goods_price'] = $value['price'];
        }
        $OrderGoods->saveAll($goods);
        // $result = db::name('order')->find($order->order_id);
        // $result['isNeedLogistics'] = 1;
        // $result['goods_price'] = (int)$result['goods_price'];
        // $result['shipping_price'] = (int)$result['shipping_price'];
       // 提交事务
         Db::commit();
            return ['data' => [], 'code' => 200, 'msg' => '下单成功', 'status' => true];
        } catch (\Exception $e) {
            dump($e->getMessage());
            // 回滚事务
            Db::rollback();
        }

    }

    public function close(){
        $param = input('post.');
        $param['status'] = 6;
        $data = $this->OrderModel->saveOrder($param);
        if($data){
            return ['data' => $data, 'code' => 200, 'msg' => '更新成功', 'status' => true];
        }else{
            return ['data' => [], 'code' => 400, 'msg' => '订单不存在', 'status' => false];
        }
    }

    public function Delivery(){
        $param = input('post.');
        $param['status'] = 3;
        $data = $this->OrderModel->saveOrder($param);
        if($data){
            return ['data' => $data, 'code' => 200, 'msg' => '更新成功', 'status' => true];
        }else{
            return ['data' => [], 'code' => 400, 'msg' => '订单不存在', 'status' => false];
        }
    }

    public function OrderList(){
        $param = input('post.');
        $validate = [
            'uid' => 'require',
        ];
        $result = $this->validate($param, $validate);
        if (true !== $result) {
            return ['data' => '', 'code' => 400, 'msg' => '参数不正确或者参数不全', 'status' => false];
        }
        $data = $this->OrderModel->getParkOrderList($param);
        if($data){
            return ['data' => $data, 'code' => 200, 'msg' => '查询成功', 'status' => true];
        }else{
            return ['data' => [], 'code' => 400, 'msg' => '订单不存在', 'status' => false];
        }
    }
}